<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单据编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="源单编号" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          placeholder="请输入源单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="buyOrderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="30" label="">
        <template slot-scope="scope">
          <el-radio
            class="radio"
            :label="scope.row"
            v-model="selectCgddRow"
          >&emsp;&emsp;&emsp
          </el-radio>
        </template>
      </el-table-column>
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column
        label="单据编号"
        align="center"
        prop="code"
        width="200"
      >

        <template slot-scope="scope">
          <el-button type="text" @click="info(scope.row)">{{
            scope.row.code
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="源单编号" align="center" prop="sourceCode" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="预付金额" align="center" prop="advanceAmount" width="100"/>
      <el-table-column label="已入库数量" align="center" prop="inventoryQuantity" width="100" />
      <el-table-column label="已入库金额" align="center" prop="inventoryAmount" width="100"/>
      <el-table-column label="已结算金额" align="center" prop="paidAmount" width="100" />
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.storeStatus == 0">未支付</span>
          <span v-if="scope.row.storeStatus == 1">部分支付</span>
          <span v-if="scope.row.storeStatus == 2">完全支付</span>
        </template>
      </el-table-column>
      <el-table-column label="入库状态" align="center" prop="storeStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.storeStatus == 0">未入库</span>
          <span v-if="scope.row.storeStatus == 1">部分入库</span>
          <span v-if="scope.row.storeStatus == 2">完全入库</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单据日期"
        align="center"
        prop="docTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据阶段" align="center" prop="docStage">
        <template slot-scope="scope">
          <span v-if="scope.row.docStage == 0">编制完</span>
          <span v-if="scope.row.docStage == 1">执行中</span>
          <span v-if="scope.row.docStage == 2">执行完</span>
        </template>
      </el-table-column>

      <el-table-column label="制单人" align="center" prop="docMakeUserName" />
      <el-table-column label="供应商" align="center" prop="supName" />
      <el-table-column label="业务员" align="center" prop="businessUserName" />
      <el-table-column label="审核结果" align="center" prop="approvalResult">
        <template slot-scope="scope">
          <!--          <el-tag  v-if="scope.row.approvalResult == 0 || scope.row.approvalResult == undefined || scope.row.approvalResult == null">待审核</>-->
          <el-tag type="success" v-if="scope.row.approvalResult == 1"
            >审核通过</el-tag
          >
          <el-tag type="danger" v-if="scope.row.approvalResult == 2"
            >审核不通过</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="审批意见" align="center" prop="approvalRemark" />
      <el-table-column label="审核人" align="center" prop="approvalUserName" />
      <el-table-column label="是否生效" align="center" prop="isEffect">
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.isEffect == 0 ||
              scope.row.isEffect == undefined ||
              scope.row.isEffect == null
            "
            >否</span
          >
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关闭" align="center" prop="isClose">
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.isClose == 0 ||
              scope.row.isClose == undefined ||
              scope.row.isClose == null
            "
            >否</span
          >
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="isCancel">
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.isCancel == 0 ||
              scope.row.isCancel == undefined ||
              scope.row.isCancel == null
            "
            >否</span
          >
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  listBuyOrder,
  getBuyOrder,
  delBuyOrder,
  addBuyOrder,
  updateBuyOrder,
  addBuyOrderPlus,
  updateBuyOrderPlus,
  approvalBuyOrder,
} from "@/api/caigou/buyOrder";
import { listComparePriceGoodsByComparePriceCode } from "@/api/caigou/buyComparePriceGoods";
import { listSupplies } from "@/api/basedata/supplies";
import SelectUser from "@/views/caigou/buyOrder/SelectUser.vue";
import SelectGoods from "@/views/caigou/buyOrder/SelectGoods.vue";
import SelectBjd from "@/views/caigou/buyOrder/SelectBjd.vue";
import Menu from "@/views/system/menu/index.vue";
import MyNumberInput from "@/views/caigou/gysbj/MyNumberInput.vue";
import { listBuyOrderGoods } from "@/api/caigou/buyOrderGoods";
import { code } from "quill/ui/icons";

//合并两个数组 通过一个唯一的键
function mergeAndDeduplicate(array1, array2, uniqueKey) {
  const uniqueObjects = new Set();
  const mergedArray = [...array1, ...array2].reduce((acc, obj) => {
    if (!uniqueObjects.has(obj[uniqueKey])) {
      uniqueObjects.add(obj[uniqueKey]);
      acc.push(obj);
    }
    return acc;
  }, []);
  return mergedArray;
}

export default {
  name: "BuyOrder",
  components: { MyNumberInput, Menu, SelectUser, SelectGoods, SelectBjd },
  props:['params'],
  data() {
    return {
      selectCgddRow:null,
      isApproval: false,
      isInfo: false,
      selectOrderGoodList: [],
      selectBjdGoodList: [],
      bjdGoodList: [],
      selectBjdList: [],
      bjdList: [],
      selectBjdDialogVisible: false,
      tableIndexTemp: 0,
      selectGoodsDialogVisible: false,
      // 订单商品
      orderGoods: {
        id: null,
        buyOrderCode: "",
        sourceCode: "",
        goodsId: null,
        price: null,
        tax: 0,
        discount: 1,
        purchaseQuantity: null,
        purchaseAmount: null,
        inventoryQuantity: null,
        paidAmount: null,
      },
      // 订单商品列表
      orderGoodsList: [],
      activeName: "second",
      // 选中的用户
      selectUserRow: {},
      // 选择用户的Dialog
      selectUserDialogVisible: false,
      //供应商数组
      supplierList: [],
      isFormMore: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      buyOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        sourceCode: null,
        totalAmount: null,
        payStatus: null,
        storeStatus: null,
        docTime: null,
        docStage: null,
        docMakeUserId: null,
        supId: null,
        businessUserId: null,
        approvalResult: 1,
        approvalRemark: null,
        approvalUserId: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        checkAmount:true
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "单据编号不能为空", trigger: "blur" },
        ],
        docTime: [
          { required: true, message: "单据日期不能为空", trigger: "blur" },
        ],
        businessUserId: [
          { required: true, message: "业务员不能为空", trigger: "blur" },
        ],
        supId: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
        purchaseQuantity: [
          {
            required: true,
            message: "采购数量必须为数字",
            transform: function (value) {
              return value === "" ? 0 : Number(value);
            },
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {},
  methods: {
    setSupId(supId){
      this.queryParams.supId = supId;
      this.getList();
    },
    returnSelectCgddList(){
      console.log("aaaa",this.selectCgddRow)
      let arr = [];
      if (this.selectCgddRow != null){
        arr.push(this.selectCgddRow);
      }
      return arr;
    },
    submitFormApproval() {
      if (
        this.form.approvalResult == null ||
        this.form.approvalResult == undefined ||
        this.form.approvalResult == ""
      ) {
        this.$modal.msgWarning("选择审核结果");
        return;
      }
      if (this.form.approvalResult == 1) {
        this.form.isEffect = 1;
        this.form.docStage = 1;
      } else if (this.form.approvalResult == 2) {
        this.form.isEffect = 0;
        this.form.docStage = 2;
      }

      approvalBuyOrder(this.form).then((response) => {
        this.$modal.msgSuccess("审核成功");
        this.open = false;
        this.getList();
      });
    },
    approval(row) {
      this.open = true;
      this.handleUpdate(row);
      this.isApproval = true;
      this.isInfo = true;
    },
    info(row) {
      this.isInfo = true;
      this.initBaseData();
      this.reset();
      const id = row.id || this.ids;
      getBuyOrder(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "查看采购订单";
        this.getBuyOrderGoodsList(this.form.code);
      });
    },
    supSelectChanged() {
      this.orderGoodsList = [];
      // this.selectBjdGoodList = [];
    },
    // 检查是否可选
    cgdGoodsListCheckSelect(row, index) {
      /**
       * row：当前行数据
       * index：当前第几位
       */
      let isChecked = true;
      if (row.supId == this.form.supId) {
        // 判断里面是否存在某个参数
        isChecked = true;
      } else {
        isChecked = false;
      }
      return isChecked;
    },
    removeOrderGoods() {
      let filterArr = [];
      this.selectOrderGoodList.forEach((a) => {
        filterArr = this.orderGoodsList.filter(
          (obj) => obj.goodsId !== a.goodsId
        );
        this.orderGoodsList = filterArr;
      });
    },
    handleSelectionChangeOrderGoodsList(val) {
      console.log(val);
      this.selectOrderGoodList = val;
    },
    handleSelectionChangeCgdGoodsList(val) {
      this.selectBjdGoodList = val;
    },
    addBjdGoodListToOrderGoodsList() {
      if (this.selectBjdGoodList.length == 0) {
        return;
      }
      this.orderGoodsList = [];
      this.selectBjdGoodList.forEach((g) => {
        this.orderGoodsList.push({
          ...g,
          purchaseQuantity: g.number,
          discount: 1,
          buyOrderCode: this.form.code,
        });
      });
    },
    // 根据比价单code 查询 报价单的商品
    searchBjdByCode() {
      let codeArr = [];
      this.bjdList.forEach((a) => {
        codeArr.push(a.code);
      });
      if (codeArr.length > 0) {
        listComparePriceGoodsByComparePriceCode(codeArr).then((res) => {
          console.log(res);
          this.bjdGoodList = res.data;
        });
      } else {
        this.bjdGoodList = [];
      }
    },
    removeBjd() {
      let filterArr = [];
      this.selectBjdList.forEach((a) => {
        filterArr = this.bjdList.filter((obj) => obj.id !== a.id);
        this.bjdList = filterArr;
      });
      this.searchBjdByCode();
    },
    handleSelectionChangeCgd(val) {
      console.log(val);
      this.selectBjdList = val;
    },
    sureSelectBjd() {
      let returnBjdList = this.$refs.SelectBjdComponent.returnBjdList();
      if (this.bjdList.length == 0) {
        this.bjdList = returnBjdList;
      } else {
        const result = mergeAndDeduplicate(returnBjdList, this.bjdList, "id");
        console.log(result);
        this.bjdList = result;
      }
      console.log(returnBjdList);
      this.selectBjdDialogVisible = false;
      this.searchBjdByCode();
    },
    cancelSelectBjd() {
      this.selectBjdDialogVisible = false;
    },
    //添加比价单
    addBjd() {
      this.selectBjdDialogVisible = true;
    },
    cancelSelectGoods() {
      this.selectGoodsDialogVisible = false;
    },
    sureSelectGoods() {
      let returnGoods = this.$refs.SelectGoodsComponent.returnGoods();

      this.$set(this.orderGoodsList, this.tableIndexTemp, {
        ...this.orderGoods,
        purchaseQuantity: 1,
        buyOrderCode: this.form.code,
        goodsId: returnGoods.id,
        price: 0,
        proName: returnGoods.proName,
        typeName: returnGoods.typeName,
        unitName: returnGoods.unitName,
      });

      this.selectGoodsDialogVisible = false;
      // console.log(this.orderGoodsList)
    },
    selectGoods(tableIndexTemp) {
      console.log("tableIndexTemp", tableIndexTemp);
      this.tableIndexTemp = tableIndexTemp;
      this.selectGoodsDialogVisible = true;
    },
    addGoods() {
      if (this.orderGoodsList.length == 0) {
        this.orderGoodsList.push(this.orderGoods);
        return;
      }
      let lastGoodsId =
        this.orderGoodsList[this.orderGoodsList.length - 1].goodsId;
      if (
        lastGoodsId == undefined ||
        lastGoodsId == null ||
        lastGoodsId == ""
      ) {
        this.$modal.msgWarning("请选择商品");
        return;
      }
      this.orderGoodsList.push(this.orderGoods);
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 确认选择用户
    sureSelectUser() {
      let returnUser = this.$refs.selectUserComponent.returnUser();
      console.log("sureSelectUser", returnUser);
      if (returnUser == null || returnUser == undefined) {
        this.$modal.msgWarning("请选择用户");
        return;
      }
      this.selectUserRow = returnUser;
      this.form.businessUserId = returnUser.userId;
      this.form.businessUserName = returnUser.nickName;
      this.selectUserDialogVisible = false;
    },
    // 取消选择用户
    cancelSelectUser() {
      this.selectUserDialogVisible = false;
    },
    selectUser() {
      this.selectUserDialogVisible = true;
    },
    // 新增初始化数据
    initBaseData() {
      //获取所有供应商
      listSupplies().then((res) => {
        this.supplierList = res.rows;
      });
      this.orderGoodsList = [];
      this.bjdList = [];
      this.bjdGoodList = [];
      this.isApproval = false;
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listBuyOrder(this.queryParams).then((response) => {
        this.buyOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.isApproval = false;
      this.open = false;
      this.isInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: "CGDD-" + Date.now(),
        sourceCode: null,
        totalAmount: null,
        payStatus: null,
        storeStatus: null,
        docTime: null,
        docStage: null,
        docMakeUserId: null,
        supId: null,
        businessUserId: null,
        approvalResult: null,
        approvalRemark: null,
        approvalUserId: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
      this.initBaseData();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.initBaseData();
      this.reset();
      const id = row.id || this.ids;
      getBuyOrder(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
        this.getBuyOrderGoodsList(this.form.code);
      });
    },
    getBuyOrderGoodsList(code) {
      listBuyOrderGoods({
        buyOrderCode: code,
        pageSize: 500,
      }).then((res) => {
        console.log(res);
        this.orderGoodsList = res.rows;
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.isInfo) {
        this.isInfo = false;
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            this.form.updateBy = this.$store.getters.name;
            updateBuyOrderPlus({
              buyOrder: this.form,
              buyOrderGoods: this.orderGoodsList,
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.$store.getters.name;
            addBuyOrderPlus({
              buyOrder: this.form,
              buyOrderGoods: this.orderGoodsList,
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.open = false;
              this.getList();
              this.orderGoodsList = [];
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除采购订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBuyOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "caigou/buyOrder/export",
        {
          ...this.queryParams,
        },
        `buyOrder_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
